//
//  AppDelegate.m
//  SoundPill
//
//  Created by 宋旭东®Des on 15/1/17.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//
#import "nullViewController.h"
#import "AppDelegate.h"
#import "PlazzViewController.h"
#import "FindViewController.h"
#import "PersonViewController.h"
#import "TGImageTool.h"
#import "MozTopAlertView.h"
#import "LauchViewController.h"
#import "My_ViewController.h"
#import "RecordViewController.h"
#import "recordMenu.h"
#import "userInformationViewController.h"
#import "AttentionPersonViewController.h"
#import "upDeviceToken.h"
#import "playerTableViewController.h"
#import "JCAlertView.h"
#import "IsLogout.h"
#import "registryEditController.h"

#define kAppKey @"2054753137"
#define kRedirectURI @"http://sns.whalecloud.com/sina2/callback"
@interface AppDelegate ()<UITabBarControllerDelegate,UIAlertViewDelegate>
{
    recordMenu *menu;
    UIButton *recordBtn;
    BOOL _chack;
}
@property (strong, nonatomic) NSUserDefaults *user;
@property (strong, nonatomic) PlazzViewController *plaza;
@end

@implementation AppDelegate

+(instancetype)shareDelegate
{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [WXApi handleOpenURL:url delegate:self];
}
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    ///读取网页跳转信息
    if ([url.scheme isEqualToString:@"soundlab"]) {
        NSString *string = [url.query substringFromIndex:3];
        [self getCurrentVC:string];
        return YES;
    } else if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
//            NSLog(@"result = %@",resultDic);
        }];
        return YES;
    } else if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回authCode
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
//            NSLog(@"result = %@",resultDic);
        }];
        return YES;
    } else {
        return  [WXApi handleOpenURL:url delegate:self];
    }
}
#pragma mark -
- (void)onReq:(BaseReq *)req
{
    
}
- (void)onResp:(BaseResp *)resp
{
    
}
#pragma mark -
- (void)getCurrentVC:(NSString *)string
{
    MMDrawerController *mmd = (MMDrawerController *)self.window.rootViewController;
    if (mmd.openSide == 2) {
//        当前页面在播放页
        UINavigationController *navigation =(UINavigationController *)mmd.rightDrawerViewController;
        if ([navigation.visibleViewController isKindOfClass:[playerTableViewController class]]) {
            playerTableViewController *player = (playerTableViewController *)navigation.visibleViewController;
            if (![player.workID isEqualToString:string]) {
                //如果不是当前正在播放的作品 刷新播放页面
                [self requestPlayerInfo:string player:player];
            } else {
                //不做任何操作
            }
        } else {
            [navigation popToRootViewControllerAnimated:YES];
            playerTableViewController *player = (playerTableViewController *)navigation.visibleViewController;
//            判断当前播放作品是否与所分享的作品相同
            if (![player.workID isEqualToString:string]) {
                [self requestPlayerInfo:string player:player];
            }
//            如果相同不操作，否则刷新播放页面
        }
    } else {
//        当前页面不在播放页
        [self drawToPlayer:mmd workid:string];
    }
}
- (void)getcurrentVcToUser:(NSString *)userid
{
    MMDrawerController *mmd = (MMDrawerController *)self.window.rootViewController;
    if (mmd.openSide == 2) {
        [mmd closeDrawerAnimated:YES completion:^(BOOL finished) {
            UITabBarController *tab = (UITabBarController *)mmd.centerViewController;
            UINavigationController *nav = (UINavigationController *)tab.selectedViewController;
            NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
            //读取字典类型NSDictionary类型的数据
            NSString *uid = [userDefaultes stringForKey:@"uid"];
            if (![userid isEqualToString: uid] ) {
                userInformationViewController *otherSelfVC = [[userInformationViewController alloc]initWithSelfUid:userid];
                [nav pushViewController:otherSelfVC animated:YES];
            }else if([userid isEqualToString: uid]){
                //自动跳到我的
                if (tab.selectedIndex == 4) {
                    UINavigationController *selfNav = (UINavigationController *)tab.selectedViewController;
                    [selfNav popToRootViewControllerAnimated:YES];
                } else {
                    [tab setSelectedIndex:4];
                }
            }
        }];
    } else {
        UITabBarController *tab = (UITabBarController *)mmd.centerViewController;
        UINavigationController *nav = (UINavigationController *)tab.selectedViewController;
        NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
        //读取字典类型NSDictionary类型的数据
        NSString *uid = [userDefaultes stringForKey:@"uid"];
        if (![userid isEqualToString: uid] ) {
            userInformationViewController *otherSelfVC = [[userInformationViewController alloc]initWithSelfUid:userid];
            [nav pushViewController:otherSelfVC animated:YES];
        }else if([userid isEqualToString: uid]){
            //自动跳到我的
            if (tab.selectedIndex == 4) {
                UINavigationController *selfNav = (UINavigationController *)tab.selectedViewController;
                [selfNav popToRootViewControllerAnimated:YES];
            } else {
                [tab setSelectedIndex:4];
            }
        }
    }
    
}
- (void)drawToPlayer:(MMDrawerController *)mmd workid:(NSString *)string
{
    UINavigationController *nv = (UINavigationController *)mmd.rightDrawerViewController;
    playerTableViewController *player = (playerTableViewController *)nv.topViewController;
    [self requestPlayerInfo:string player:player];
    [mmd toggleDrawerSide:MMDrawerSideRight animated:YES completion:^(BOOL finished) {
    }];
}
- (void)requestPlayerInfo:(NSString *)string player:(playerTableViewController *)player
{
    NSString *CinemeID = string;
    Player_ShowModel *playModel = [Player_ShowModel sharedInstance];
    NSString *showURL = [NSString stringWithFormat:@"http://123.57.1.143/api/work/%@/show", CinemeID];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSString *head = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:head forHTTPHeaderField:@"authorization"];
    [manager GET:showURL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = (NSDictionary *)responseObject;
        NSDictionary *dataDic = [dic valueForKey:@"data"];
        NSDictionary *linksDic = [dic valueForKey:@"links"];
        [playModel setValuesForKeysWithDictionary:dataDic];
        if ([[dic allKeys] containsObject:@"meta"]) {
            NSDictionary *meta = [dic valueForKey:@"meta"];
            NSString *userAvatar = [meta valueForKey:@"userAvatar"];
            player.locUserAvatar = userAvatar;
//            NSArray *array = [meta valueForKey:@"playlist"];
//            player.playList = [NSMutableArray arrayWithArray:array]
            ;
            playModel.comment_count = [meta valueForKey:@"count"];
            ;
        }
        player.waveform = [linksDic valueForKey:@"waveform"];
        player.workID = CinemeID;
        player.isSelf = NO;
        [player reloadViews:playModel];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];

}
#pragma mark -
- (void)chooseRootViewController
{
    if ([_user objectForKey:@"token"] == nil)  {
       LauchViewController *login = [[LauchViewController alloc] init];
        [self.window setRootViewController:login];
    } else {
        [self chooseTabBarController];
    }
}

- (void)chooseTabBarController
{
    //首页
    self.plaza = [[PlazzViewController alloc] init];
    UINavigationController *plazaNavgation = [[UINavigationController alloc] initWithRootViewController:_plaza];
    UIImage *homeSel = [UIImage imageNamed:@"tab_home_inverse"];
    UIImage *homeDis = [UIImage imageNamed:@"tab_home_normal"];
    homeSel = [homeSel imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    _plaza.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"首页" image: homeDis selectedImage:homeSel];
    _plaza.title = @"首页";
    //发现
    FindViewController *Find = [[FindViewController alloc] init];
    UINavigationController *FindNav = [[UINavigationController alloc] initWithRootViewController:Find];
    UIImage *findSel = [UIImage imageNamed:@"tab_find_inverse"];
    UIImage * findDis = [UIImage imageNamed:@"tab_find_normal"];
    findSel = [findSel imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    Find.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"LABx" image: findDis selectedImage:findSel];
//    Find.title = @"发现";
    //音乐人
    PersonViewController *person = [[PersonViewController alloc] init];
    UINavigationController *personNav = [[UINavigationController alloc] initWithRootViewController:person];
    UIImage *personSel = [UIImage imageNamed:@"tab_person_inverse"];
    UIImage * personDis = [UIImage imageNamed:@"tab_person_normal"];
    personSel = [personSel imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    person.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"圈子" image: personDis selectedImage:personSel];
//    person.title = @"人物";
    //新我的
    NSString *uid = [_user valueForKey:@"uid"];
    My_ViewController *oneself = [[My_ViewController alloc] initWithSelfUid:uid];
    UINavigationController *myselfNavgation = [[UINavigationController alloc] initWithRootViewController:oneself];
    UIImage *userSel = [UIImage imageNamed:@"tab_user_inverse"];
    UIImage *userDis = [UIImage imageNamed:@"tab_user_normal"];
    userSel = [userSel imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    oneself.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"我的" image: userDis selectedImage:userSel];
    oneself.title = @"我的";
    
    nullViewController *nullv = [[nullViewController alloc] init];
    //tabBar
    NSArray *tabArray =[NSArray arrayWithObjects:plazaNavgation, FindNav, nullv, personNav, myselfNavgation, nil];
    UITabBarController *tabBar = [[UITabBarController alloc] init];
    tabBar.delegate = self;
    [tabBar setViewControllers:tabArray animated:YES];
    tabBar.selectedIndex = 0;
    CGRect frame = CGRectMake(0, 0, self.window.frame.size.width, 50);
    UIView * bv = [[UIView alloc] initWithFrame:frame];
    bv.backgroundColor = [UIColor blackColor];
    [tabBar.tabBar insertSubview:bv atIndex:0];
    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil] forState:UIControlStateSelected];
    
    recordBtn = [[UIButton alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width / 2 - (bv.frame.size.height / 2) + 5, 0, bv.frame.size.height + 5, bv.frame.size.height)];
    recordBtn.center = CGPointMake(frame.size.width/2, frame.size.height / 2);
    [recordBtn setBackgroundImage:[UIImage imageNamed:@"tab_red"] forState:UIControlStateNormal];
    [recordBtn addTarget:self action:@selector(goToRecorder) forControlEvents:UIControlEventTouchUpInside];
    [tabBar.tabBar addSubview:recordBtn];
    
//    PlayerViewController *play = [[PlayerViewController alloc] init];
    playerTableViewController *player = [playerTableViewController sharedInstance];
    UINavigationController *playnav = [[UINavigationController alloc] initWithRootViewController:player];
    
    MMDrawerController *mmdrawer = [[MMDrawerController alloc] initWithCenterViewController:tabBar rightDrawerViewController:playnav];
    
    [mmdrawer setShowsShadow:NO];
    [mmdrawer setMaximumRightDrawerWidth:self.window.size.width];
    [self.window setRootViewController:mmdrawer];
   
//    登陆环信
    NSString *userid = [[NSUserDefaults standardUserDefaults] valueForKey:@"uid"];
    NSString *telNum = [[NSUserDefaults standardUserDefaults] valueForKey:@"telNumber"];
    NSString *EMid = [NSString stringWithFormat:@"%@%@",userid,telNum];
    NSString *EMpassword = [NSString md5HexDigest:EMid];
    BOOL isAutoLogin = [EMClient sharedClient].options.isAutoLogin;
    if (!isAutoLogin) {
        EMError *error = [[EMClient sharedClient] loginWithUsername:uid     password:EMpassword];
        if (!error)
        {
//            NSLog(@"登陆");
            [[EMClient sharedClient].options setIsAutoLogin:YES];
        } else {
//            NSLog(@"%@",error.errorDescription);
        }
    }
    [self createMusicStateView];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    _chack = YES;
//    打开应用次数
    NSNumber *launchCount = [[NSUserDefaults standardUserDefaults] valueForKey:@"lanuchCount"];
    if (launchCount == nil) {
        launchCount = [NSNumber numberWithInt:1];
        [[NSUserDefaults standardUserDefaults] setValue:launchCount forKey:@"lanuchCount"];
    } else {
        launchCount = [NSNumber numberWithInt:launchCount.intValue + 1];
        [[NSUserDefaults standardUserDefaults] setValue:launchCount forKey:@"lanuchCount"];
    }

    [NSThread sleepForTimeInterval:0.8];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(disMissMenu:) name:@"disMissMenu" object:nil];

    [self thirdPartRegiesterFunc];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.user = [NSUserDefaults standardUserDefaults];
    [self.window makeKeyAndVisible];
    [self chooseRootViewController];
//    [IsLogout userIsLogout:_plaza Alert:YES];
    
    self.isForeground = [NSNumber numberWithBool:YES];
    [self pushRegisterFuncWithApplication:application Options:launchOptions];
    return YES;
}
- (void)thirdPartRegiesterFunc
{
    //    友盟统计
    [MobClick startWithAppkey:@"54d314e1fd98c566b400025b" reportPolicy:REALTIME channelId:nil];
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
    //微信
    [WXApi registerApp:@"wxbf432e4195450eed"];
    //微博
    [WeiboSDK enableDebugMode:YES];
    [WeiboSDK registerApp:kAppKey];
    //    环信
    EMOptions *options = [EMOptions optionsWithAppkey:@"soundlab#soundlab"];
    options.apnsCertName = @"push";
    [[EMClient sharedClient] initializeSDKWithOptions:options];
}
- (void)pushRegisterFuncWithApplication:(UIApplication *)application Options:(NSDictionary *)launchOptions
{
    if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
    {
        //IOS8
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        //创建UIUserNotificationSettings，并设置消息的显示类类型
        UIUserNotificationSettings *notiSettings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound) categories:nil];
        [application registerUserNotificationSettings:notiSettings];
        
    } else { // ios7
        [application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge                                       |UIRemoteNotificationTypeSound                                      |UIRemoteNotificationTypeAlert
                                                         |UIRemoteNotificationTypeSound)];
    }
    if (launchOptions) {
        NSDictionary* pushNotificationKey = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        if (pushNotificationKey) {
            //这里定义自己的处理方式
            if ([[pushNotificationKey objectForKey:@"aps"] objectForKey:@"alert"]!=NULL) {
                if ([[pushNotificationKey objectForKey:@"action"] isEqualToString:@"work"]) {
                    [self getCurrentVC:[NSString stringWithFormat:@"%@",[pushNotificationKey valueForKey:@"detail"]]];
                } else if ([[pushNotificationKey objectForKey:@"action"] isEqualToString:@"people"]){
                    [self getcurrentVcToUser:[NSString stringWithFormat:@"%@",[pushNotificationKey valueForKey:@"detail"]]];
                }
            }
            
        }
    }
    [self addReachability];
    NSArray *localArray = [application scheduledLocalNotifications];
    for (UILocalNotification *noti in localArray) {
        [application cancelLocalNotification:noti];
    }
}
- (void)createMusicStateView
{
    self.playerStateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _playerStateBtn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 75,[UIScreen mainScreen].bounds.size.height - 150, 60, 60);
    _playerStateBtn.backgroundColor = [UIColor blackColor];
    [_playerStateBtn addTarget:self action:@selector(playerStateBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.window addSubview:_playerStateBtn];
    _playerStateBtn.backgroundColor = [UIColor clearColor];
    _playerStateBtn.layer.cornerRadius = 30;
    _playerStateBtn.layer.borderColor = [[UIColor whiteColor] CGColor];
    _playerStateBtn.layer.borderWidth = 3.5;
    [self setUpMusicIndicator];
}
- (void)setUpMusicIndicator
{
    self.indicator = [HCMusicIndicator shareIndicator];
    _indicator.userInteractionEnabled = NO;
    _indicator.hidesWhenStopped = NO;
    _indicator.backgroundColor = [UIColor blackColor];
    _indicator.layer.cornerRadius = 30;
    _indicator.tintColor = [UIColor whiteColor];
    if (_indicator.state != NAKPlaybackIndicatorViewStatePlaying) {
        _indicator.state = NAKPlaybackIndicatorViewStatePaused;
    } else {
        _indicator.state = NAKPlaybackIndicatorViewStatePlaying;
    }
    
    [_playerStateBtn addSubview:_indicator];
}
#pragma mark -
#pragma mark 网络监测
- (void)addReachability {
    // 监测网络情况
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    //初始化
    self.hostReach = [soundLabReachability reachabilityWithHostName:@"www.baidu.com"];
    //通知添加到Run Loop
    [self.hostReach startNotifier];
    [self updateInterfaceWithReachability:_hostReach];
}
- (void) reachabilityChanged:(NSNotification *)note
{
    soundLabReachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[soundLabReachability class]]);
    [self updateInterfaceWithReachability:curReach];
}
- (void)updateInterfaceWithReachability:(soundLabReachability *)reachability
{
    NetworkStatus netStatus = [reachability currentReachabilityStatus];
    switch (netStatus) {
        case NotReachable:
//            NSLog(@"====当前网络状态不可达=======");
            if (!_reachabilityAlert) {
                [MozTopAlertView showWithType:MozAlertTypeError text:@"无网络或信号弱，请检查你的网络设置" doText:nil doBlock:^{

                } parentView:self.window.rootViewController.view];
            }
            self.isWiFi = NO;
            break;
        case ReachableViaWiFi:
//            NSLog(@"====当前网络状态为Wifi=======");
            self.isWiFi = YES;
            break;
        case ReachableViaWWAN:
//            NSLog(@"====当前网络状态为蜂窝数据=======");
            self.isWiFi = NO;
            break;
    }
}
#pragma mark -
#pragma mark 推送代理
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    [[EMClient sharedClient] bindDeviceToken:deviceToken];
    NSString *str = [NSString stringWithFormat:@"%@", deviceToken];
    NSString *token = [[[str stringByReplacingOccurrencesOfString:@" " withString:@""] stringByReplacingOccurrencesOfString:@"<" withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""];

    self.deviceToken = token;
//    NSFileManager *manager = [NSFileManager defaultManager];
    NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [directoryPaths objectAtIndex:0];
    NSString *filePath = [documentDirectory stringByAppendingPathComponent:@"DeviceToken"];
    NSString *oldDeviceToken = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    if (![_deviceToken isEqualToString:oldDeviceToken]) {
        upDeviceToken *dev = [[upDeviceToken alloc] initWithDeviceToken:_deviceToken Uid:[_user valueForKey:@"uid"]];
        dev = nil;
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
// 应用打开状态接收消息
        //第二种情况
    if(application.applicationState != UIApplicationStateActive) {
        if ([[userInfo objectForKey:@"aps"] objectForKey:@"alert"]!=NULL) {
            if ([[userInfo objectForKey:@"action"] isEqualToString:@"work"]) {
                [self getCurrentVC:[NSString stringWithFormat:@"%@",[userInfo valueForKey:@"detail"]]];
            } else if ([[userInfo objectForKey:@"action"] isEqualToString:@"people"]){
                [self getcurrentVcToUser:[NSString stringWithFormat:@"%@",[userInfo valueForKey:@"detail"]]];
            }
        }
    }
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
//    NSLog(@"Regist fail%@",error);
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"error" message:[NSString stringWithFormat:@"Regist fail%@",error] delegate:self cancelButtonTitle:@"yes" otherButtonTitles: nil];
//    [alert show];
}
#pragma mark -
- (void)applicationWillResignActive:(UIApplication *)application {
    //挂起
    self.isForeground = [NSNumber numberWithBool:NO];
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"stopAudioPlayer" object:nil];
    signal(SIGPIPE, SIG_IGN);
    [self.hostReach stopNotifier];
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [[EMClient sharedClient] applicationDidEnterBackground:application];
//    });
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {

    [self.hostReach startNotifier];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [[EMClient sharedClient] applicationWillEnterForeground:application];
    });
//    _chack = YES;
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    self.isForeground = [NSNumber numberWithBool:YES];
   
    if (_chack == NO) {
        [IsLogout userIsLogout:_plaza Alert:NO];
    } else {
        _chack = NO;
    }
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return UIInterfaceOrientationMaskPortrait;
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
    // 清除图片缓存
    [TGImageTool clear];
}
- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
{
    if([shortcutItem.type isEqualToString:@"publish"]){
        MMDrawerController *mmd = (MMDrawerController *)self.window.rootViewController;
        if (mmd.openSide == 0) {
            [self goToRecorder];
        }
    }
}
#pragma mark -
- (void)didReceiveWeiboRequest:(WBBaseRequest *)request
{
    
}
- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    if ([response isKindOfClass:WBSendMessageToWeiboResponse.class])
    {
        WBSendMessageToWeiboResponse* sendMessageToWeiboResponse = (WBSendMessageToWeiboResponse*)response;
        NSString* accessToken = [sendMessageToWeiboResponse.authResponse accessToken];
        if (accessToken)
        {
            self.wbtoken = accessToken;
        }
        NSString* userID = [sendMessageToWeiboResponse.authResponse userID];
        if (userID) {
            self.wbCurrentUserID = userID;
        }
    }
    else if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
        self.wbtoken = [(WBAuthorizeResponse *)response accessToken];
        self.wbCurrentUserID = [(WBAuthorizeResponse *)response userID];
        self.wbRefreshToken = [(WBAuthorizeResponse *)response refreshToken];
    }
    else if ([response isKindOfClass:WBPaymentResponse.class])
    {
    }
    else if([response isKindOfClass:WBSDKAppRecommendResponse.class])
    {}
}
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    UITabBarItem *item = (UITabBarItem *)[tabBarController.tabBar.items objectAtIndex:2];
    if (item == tabBarController.tabBar.selectedItem) {
        return NO;
    } else {
        return YES;
    }
}
- (void)goToRecorder
{
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"uid"] == nil) {
        //我的
        //提示请先登陆
        [JCAlertView showTwoButtonsWithTitle:@"未登录" Message:@"登录后才能继续操作" ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"再看看" Click:^{
            
        } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"去登录" Click:^{
            [self chooseRootViewController];
        }];
    } else {
        [self showPublishMenu];
    }
}
- (void)showPublishMenu
{
    self.content = [NSMutableArray arrayWithObjects:@"音 乐",@"谈 话",nil];
    menu = [[recordMenu alloc] initWithFrame:CGRectMake(0, 0, self.window.bounds.size.width, self.window.bounds.size.height) Content:_content];
    menu.backgroundColor = [UIColor colorWithWhite:1.000 alpha:0.000];
    
    menu.contentSize = CGSizeMake(self.window.bounds.size.width * 2, 0);
    menu.scrollEnabled = NO;
    [self.window addSubview:menu];
    self.butt = [[UIButton alloc] initWithFrame:CGRectMake(recordBtn.frame.origin.x, self.window.frame.size.height, recordBtn.frame.size.width, recordBtn.frame.size.height)];
    [_butt setImage:[UIImage imageNamed:@"menuWhiteClose"] forState:UIControlStateNormal];
    [_butt addTarget:self action:@selector(disMisMenuBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.window addSubview:_butt];
    [menu ChangeItemFrame];
    [UIView animateWithDuration:0.4 animations:^{
            _butt.frame = CGRectMake(recordBtn.frame.origin.x, self.window.frame.size.height - 49, recordBtn.frame.size.width, recordBtn.frame.size.height);
            recordBtn.hidden = YES;
    } completion:^(BOOL finished) {
            
    }];
    [UIView animateWithDuration:0.4 animations:^{
        menu.backgroundColor = [UIColor colorWithWhite:0.000 alpha:0.700];
    } completion:^(BOOL finished) {
        
    }];
}
- (void)changePublish:(UITapGestureRecognizer *)recognizer
{
    UIImageView *imageView = (UIImageView *)recognizer.view;
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.5 animations:^{
            imageView.alpha = 0;
        } completion:^(BOOL finished) {
            [self showPublishMenu];
            [imageView removeGestureRecognizer:recognizer];
            [imageView removeFromSuperview];
            self.window.rootViewController.view.userInteractionEnabled = YES;
        }];
        [[NSUserDefaults standardUserDefaults] setValue:@"NO" forKey:@"is_publish_first"];
}
- (void)disMissMenu:(NSNotification *)notification
{
    self.topicString = nil;
    NSDictionary *dic = notification.object;
    NSNumber *num = [dic objectForKey:@"isStart"];
    if (num.boolValue == 1) {
        [self disMisMenuBtnClick:nil];
        NSString *str = [dic valueForKey:@"tag"];
        self.startTag = str;
        RecordViewController *record = [[RecordViewController alloc] initWithType:_startTag detile:_topicString];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:record];
        [self.window.rootViewController presentViewController:nav animated:YES completion:nil];
    }
}
- (void)disMisMenuBtnClick:(UIButton *)sender
{
    [UIView animateWithDuration:0.2 animations:^{
        menu.alpha = 0;
        [UIView animateWithDuration:0.2 animations:^{
            _butt.frame = CGRectMake(_butt.frame.origin.x, self.window.frame.size.height, _butt.frame.size.width, _butt.frame.size.height);
            [UIView animateWithDuration:0.4 animations:^{
                recordBtn.hidden = NO;
            } completion:^(BOOL finished) {
            }];
        } completion:^(BOOL finished) {
            [_butt removeFromSuperview];
        }];
    } completion:^(BOOL finished) {
        [menu removeFromSuperview];
    }];
}
- (void)playerStateBtnClick:(UIButton *)button
{
    MMDrawerController *mmd = (MMDrawerController *)self.window.rootViewController;
    UINavigationController *navigation =(UINavigationController *)mmd.rightDrawerViewController;
    if (mmd.openSide != 2) {
        //        当前页面在播放页
        if ([navigation.topViewController isKindOfClass:[playerTableViewController class]]) {
            playerTableViewController *player = (playerTableViewController *)navigation.topViewController;
            if (player.workID == nil) {
                [JCAlertView showOneButtonWithTitle:@"提示" Message:@"没有正在播放的声音" ButtonType: JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                    
                }];
            } else {
                [mmd toggleDrawerSide:MMDrawerSideRight animated:YES completion:^(BOOL finished) {
                    
                }];
            }
        }
    } else {
        [navigation popToRootViewControllerAnimated:YES];
    }
}
@end
